package light.head.controller.site;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import light.head.constant.Msg;
import light.head.constant.Parm;
import light.head.constant.Url;
import light.head.dao.site.EnergyConservationDAO;
import light.head.dao.site.NewsDAO;
import light.head.dao.site.NewsItemDAO;
import light.head.dao.site.ParkAnnouncementDAO;
import light.head.dao.site.PolicySupportDAO;
import light.head.enm.RESULT;
import light.head.framework.base.SupporterController;
import light.head.framework.entity.PageBean;
import light.head.model.EnergyConservation;
import light.head.model.News;
import light.head.model.NewsItem;
import light.head.model.ParkAnnouncement;
import light.head.model.PolicySupport;

import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.Tag;
import org.htmlparser.filters.AndFilter;
import org.htmlparser.filters.HasAttributeFilter;
import org.htmlparser.filters.TagNameFilter;
import org.htmlparser.util.NodeList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
@RequestMapping(value= Url.C_NNEWS)
public class NewsController extends SupporterController{
	private NewsDAO newsDAO;
	private NewsItemDAO itemDAO;
	private ParkAnnouncementDAO paDAO;
	private PolicySupportDAO psDAO;
	private EnergyConservationDAO ecDAO;
	@RequestMapping(value = Url.INIT)
	public ModelAndView init(HttpServletRequest request, HttpServletResponse response) throws Exception {
		return new ModelAndView(Url.NEWS_INIT);
	}

	@RequestMapping(Url.QUERY)
	public ModelAndView query(HttpServletRequest request, HttpServletResponse response) throws Exception {
		PageBean pb = createPageBean(request);
		Map<String, String> map = createQueryMapByParmName(request, Parm.TIME1, Parm.TIME2, Parm.DELETED,Parm.STARTURL,Parm.REMARK);
		if (newsDAO.findByMap(map, pb) == RESULT.SUCCESS) {
			request.setAttribute(Parm.PAGE_BEAN, pb);
		}
		return new ModelAndView(Url.NEWS_LIST);
	}

	@RequestMapping(Url.EDIT)
	public ModelAndView edit(Integer code, HttpServletRequest request, HttpServletResponse response) throws Exception {
		if (null != code) {
			News n = newsDAO.get(code);
			List<NewsItem> itemList = newsDAO.findUc(code);
			n.setItemList(itemList);
			request.setAttribute(Parm.NEWS, n);
		}
		return new ModelAndView(Url.NEWS_EDIT);
	}
	
	@RequestMapping(Url.SAVE)
	public void save(News news,HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		RESULT result = RESULT.ERROR; 
		News ns = new News();
		ns.setCt(new Date());
		ns.setDeleted(false);
		ns.setContent(news.getContent());
		ns.setK(news.getK());
		ns.setK1(news.getK1());
		ns.setStarturl(news.getStarturl());
		ns.setT(news.getT());
		ns.setV(news.getV());
		ns.setV1(news.getV1());
		ns.setWww(news.getWww());
		ns.setType(news.getType());
		ns.setRemark(news.getRemark());
		ns.setName(news.getName());
		newsDAO.add(ns);
		if (news.getStarturl() != null && news.getWww() != null && news.getT() != null && news.getK() != null && news.getV() != null 
				&& news.getContent() != null && news.getK1() != null && news.getV1() != null){
			try {
				// 查询页面新闻的  标签 以及ID
				NodeFilter filter = new AndFilter(new TagNameFilter(news.getT()), new HasAttributeFilter(news.getK(), news.getV()));
				Parser parser = new Parser();
				Parser bodyparser = new Parser();
				parser.setURL(news.getStarturl());
				parser.setEncoding(parser.getEncoding());
				//获取匹配的fileter的节点
				NodeList list = parser.extractAllNodesThatMatch(filter);
				for (int i = 0; i < list.size(); i++) {
					Tag node = (Tag) list.elementAt(i);
					for (int j = 0; j < node.getChildren().size(); j++) {
						String textstr = node.getChildren().elementAt(j).toHtml().trim();
						if (textstr.length() > 0) {
							int linkbegin=0,linkend=0,titlebegin=0,titleend=0;
							while(true){
								textstr = textstr.replaceAll("\'","\"");
								linkbegin = textstr.indexOf("href=\"",titleend);// 截取链接字符串起始位置
								//如果不存在 href了 也就结束了
								if(linkbegin <= 0) break;
								linkend = textstr.indexOf("\"",linkbegin + 6);// 截取链接字符串结束位置
								
								String sublink = textstr.substring(linkbegin + 6,linkend);
								String link = news.getWww()+sublink;
								//截取title
								titlebegin = textstr.indexOf(">",linkend);
								titleend = textstr.indexOf("</a>",titlebegin);
								String title = textstr.substring(titlebegin + 1,titleend);
								System.out.println("正在抓取 " + title);
								try {
									//匹配正文有DIV
									NodeFilter bodyfilter = new AndFilter( new TagNameFilter(news.getContent()), new HasAttributeFilter(news.getK1(), news.getV1()));
									bodyparser.setURL(link);
									bodyparser.setEncoding(bodyparser.getEncoding());
									
									NodeList bodylist = bodyparser.extractAllNodesThatMatch(bodyfilter);
									//将DIV中的标签都 去掉只留正文
									String newstextstr = bodylist.asString();
									List<NewsItem> itemList = newsDAO.findAll(link);
									if (itemList == null || itemList.size() == 0) {
										NewsItem item = new NewsItem();
										item.setUc(ns.getCode());
										item.setContent(newstextstr);
										item.setDeleted(false);
										item.setTitle(title);
										item.setUrl(link);
										result = itemDAO.add(item);
										switch (news.getType()) {
											//政策支持
											case 1:	
											case 2:
											case 3:
												PolicySupport ps = new PolicySupport();
												ps.setRt(new Date());
												ps.setTitle(title);
												ps.setContent(newstextstr);
												ps.setType(news.getType());
												ps.setUnit(news.getName());
												ps.setDeleted(false);
												ps.setCt(new Date());
												result = psDAO.add(ps);
												break;
											//公告
											case 4:
												ParkAnnouncement pa = new ParkAnnouncement();
												pa.setRt(new Date());
												pa.setTitle(title);
												pa.setContent(newstextstr);
												pa.setCn(news.getName());
												pa.setDeleted(false);
												result = paDAO.add(pa);
												break;
											//节能减排
											case 5:	
												EnergyConservation ec = new EnergyConservation();
												ec.setRt(new Date());
												ec.setTitle(title);
												ec.setContent(newstextstr);
												ec.setUnit(news.getName());
												ec.setDeleted(false);
												result = ecDAO.add(ec);
												break;
										}
									}
								} catch (Exception e) {
									System.out.println("抓取信息子页面出错，出错信息为：");
									e.printStackTrace();
								}
							}
						}
					}
				}
			} catch (Exception e) {
				System.out.println("抓取信息出错，出错信息为：");
				e.printStackTrace();
				return;
			}
		}
		if (result == RESULT.SUCCESS){
			print(response, Msg.SUCCESS);
		} else {
			print(response, Msg.ERROR);
		}
		
	}
	@RequestMapping(value = Url.DETAIL)
	public ModelAndView detail(Integer code, HttpServletRequest request, HttpServletResponse response) throws Exception {
		if (null != code) {
			News n = newsDAO.get(code);
			if (null != n) {
				List<NewsItem> list = newsDAO.findUc(code);
				n.setItemList(list);
				request.setAttribute(Parm.NEWS, n);
			}
		}
		return new ModelAndView(Url.NEWS_DETAIL);
	}
	@Autowired
	public void setNewsDAO(NewsDAO newsDAO) {
		this.newsDAO = newsDAO;
	}
	@Autowired
	public void setItemDAO(NewsItemDAO itemDAO) {
		this.itemDAO = itemDAO;
	}
	@Autowired
	public void setPaDAO(ParkAnnouncementDAO paDAO) {
		this.paDAO = paDAO;
	}
	@Autowired
	public void setPsDAO(PolicySupportDAO psDAO) {
		this.psDAO = psDAO;
	}
	@Autowired
	public void setEcDAO(EnergyConservationDAO ecDAO) {
		this.ecDAO = ecDAO;
	}
	
}
